package com.googlecode.gwtbb.server.intermediate;

import com.googlecode.gwtbb.client.shared.entity.properties.GetId;
import com.googlecode.gwtbb.server.dao.Dao;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.collections.map.Flat3Map;

import java.util.Map;
import java.util.List;
import java.util.HashMap;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Feb 5, 2009
 */
public abstract class ObjectAssembler<O extends GetId> {
	@Transactional
	public O assemble(Long id) {
		return assemble(getObjectDao().select(id));
	}

	@Transactional
	public List<O> assemble(List<O> objects) {
		int initialCapacity = objects.size() * 2;
		Map<Long, O> objectMap = new HashMap<Long, O>(initialCapacity);

		for (O o : objects)
			doAssemble(o, objectMap);

		return objects;
	}

	@Transactional
	public O assemble(O object) {
		//noinspection unchecked
		Map<Long, O> objectMap = new Flat3Map();
		return doAssemble(object, objectMap);
	}

	public abstract O doAssemble(O object, Map<Long, O> objectMap);

	public abstract Dao<O> getObjectDao();
}
